<template>
  <view class="order-detail-page">
    <view v-if="order" class="order-content">
      <!-- 订单状态卡片 -->
      <view class="status-card card">
        <view class="status-header">
          <view class="status-icon" :class="getStatusClass(order.status)">
            <text class="icon">{{ getStatusIcon(order.status) }}</text>
          </view>
          <view class="status-info">
            <text class="status-title">{{ getStatusTitle(order.status) }}</text>
            <text class="status-desc">{{ getStatusDesc(order.status) }}</text>
          </view>
        </view>
        
        <view v-if="order.status === 'in_progress'" class="remaining-time">
          <text class="time-label">剩余时间</text>
          <text class="time-value">{{ remainingTime }}</text>
        </view>
      </view>
      
      <!-- 座位信息卡片 -->
      <view class="seat-card card">
        <view class="card-header">
          <text class="card-title">座位信息</text>
        </view>
        
        <view class="seat-info">
          <view class="seat-main">
            <text class="seat-number">{{ order.seatNumber }}</text>
            <text class="seat-area">{{ getSeatArea(order.seatId) }}</text>
          </view>
          <view class="seat-price">
            <text class="price-text">¥{{ order.hourlyRate }}/小时</text>
          </view>
        </view>
      </view>
      
      <!-- 时间信息卡片 -->
      <view class="time-card card">
        <view class="card-header">
          <text class="card-title">时间信息</text>
        </view>
        
        <view class="time-details">
          <view class="time-item">
            <text class="time-label">开始时间</text>
            <text class="time-value">{{ formatTime(order.startTime, 'YYYY-MM-DD HH:mm') }}</text>
          </view>
          <view class="time-item">
            <text class="time-label">结束时间</text>
            <text class="time-value">{{ formatTime(order.endTime, 'YYYY-MM-DD HH:mm') }}</text>
          </view>
          <view class="time-item">
            <text class="time-label">使用时长</text>
            <text class="time-value">{{ order.duration }}小时</text>
          </view>
          <view v-if="order.actualEndTime" class="time-item">
            <text class="time-label">实际结束</text>
            <text class="time-value">{{ formatTime(order.actualEndTime, 'YYYY-MM-DD HH:mm') }}</text>
          </view>
        </view>
      </view>
      
      <!-- 费用明细卡片 -->
      <view class="cost-card card">
        <view class="card-header">
          <text class="card-title">费用明细</text>
        </view>
        
        <view class="cost-details">
          <view class="cost-item">
            <text class="cost-label">基础费用</text>
            <text class="cost-value">¥{{ order.baseAmount?.toFixed(2) || (order.duration * order.hourlyRate).toFixed(2) }}</text>
          </view>
          <view v-if="order.discountAmount > 0" class="cost-item discount">
            <text class="cost-label">优惠减免</text>
            <text class="cost-value">-¥{{ order.discountAmount.toFixed(2) }}</text>
          </view>
          <view class="cost-divider"></view>
          <view class="cost-item total">
            <text class="cost-label">实付金额</text>
            <text class="cost-value">¥{{ order.totalAmount.toFixed(2) }}</text>
          </view>
        </view>
      </view>
      
      <!-- 支付信息卡片 -->
      <view class="payment-card card">
        <view class="card-header">
          <text class="card-title">支付信息</text>
        </view>
        
        <view class="payment-details">
          <view class="payment-item">
            <text class="payment-label">支付方式</text>
            <text class="payment-value">{{ getPaymentMethodText(order.paymentMethod) }}</text>
          </view>
          <view class="payment-item">
            <text class="payment-label">支付状态</text>
            <view class="payment-status" :class="order.paymentStatus">
              {{ getPaymentStatusText(order.paymentStatus) }}
            </view>
          </view>
          <view class="payment-item">
            <text class="payment-label">订单号</text>
            <text class="payment-value">{{ order.id }}</text>
          </view>
          <view class="payment-item">
            <text class="payment-label">创建时间</text>
            <text class="payment-value">{{ formatTime(order.createdAt, 'YYYY-MM-DD HH:mm:ss') }}</text>
          </view>
        </view>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-buttons">
        <button 
          v-if="order.status === 'pending'" 
          class="btn btn-secondary"
          @click="cancelOrder"
        >
          取消订单
        </button>
        <button 
          v-if="order.status === 'in_progress'" 
          class="btn btn-secondary"
          @click="extendOrder"
        >
          续费延时
        </button>
        <button 
          v-if="order.status === 'in_progress'" 
          class="btn btn-primary"
          @click="endOrder"
        >
          结束使用
        </button>
        <button 
          v-if="order.status === 'completed'" 
          class="btn btn-secondary"
          @click="rateOrder"
        >
          评价订单
        </button>
        <button 
          class="btn btn-primary"
          @click="rebookOrder"
        >
          再次预约
        </button>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view v-else class="loading-state">
      <view class="loading-icon"></view>
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useOrderStore } from '@/stores/order'
import { useSeatStore } from '@/stores/seat'
import { useUserStore } from '@/stores/user'
import { formatTime, showError, showSuccess, showConfirm } from '@/utils/common'
import { checkPageAccess } from '@/utils/auth'

const orderStore = useOrderStore()
const seatStore = useSeatStore()
const userStore = useUserStore()

// 响应式数据
const order = ref(null)
const remainingTimeInterval = ref(null)

// 计算属性
const remainingTime = computed(() => {
  if (!order.value || order.value.status !== 'in_progress') return '00:00:00'
  const seconds = orderStore.getRemainingTime(order.value)
  return orderStore.formatRemainingTime(seconds)
})

// 方法
const getStatusClass = (status) => {
  const statusMap = {
    pending: 'status-pending',
    confirmed: 'status-confirmed',
    in_progress: 'status-progress',
    completed: 'status-completed',
    cancelled: 'status-cancelled'
  }
  return statusMap[status] || ''
}

const getStatusIcon = (status) => {
  const iconMap = {
    pending: '⏳',
    confirmed: '✅',
    in_progress: '🎮',
    completed: '✨',
    cancelled: '❌'
  }
  return iconMap[status] || '❓'
}

const getStatusTitle = (status) => {
  const titleMap = {
    pending: '等待确认',
    confirmed: '预约成功',
    in_progress: '正在使用',
    completed: '已完成',
    cancelled: '已取消'
  }
  return titleMap[status] || '未知状态'
}

const getStatusDesc = (status) => {
  const descMap = {
    pending: '订单正在处理中，请稍候',
    confirmed: '请按时到达指定座位',
    in_progress: '正在享受游戏时光',
    completed: '感谢您的使用',
    cancelled: '订单已被取消'
  }
  return descMap[status] || ''
}

const getSeatArea = (seatId) => {
  const seat = seatStore.getSeatById(seatId)
  return seat ? seat.area : '未知区域'
}

const getPaymentMethodText = (method) => {
  const methodMap = {
    wechat: '微信支付',
    alipay: '支付宝',
    balance: '余额支付'
  }
  return methodMap[method] || '未知'
}

const getPaymentStatusText = (status) => {
  const statusMap = {
    pending: '待支付',
    paid: '已支付',
    refunded: '已退款'
  }
  return statusMap[status] || '未知'
}

const cancelOrder = async () => {
  const confirmed = await showConfirm('确定要取消这个订单吗？')
  if (confirmed) {
    const result = await orderStore.cancelOrder(order.value.id)
    if (result.success) {
      order.value.status = 'cancelled'
      showSuccess('订单已取消')
    } else {
      showError(result.message || '取消失败')
    }
  }
}

const extendOrder = () => {
  uni.showModal({
    title: '续费功能',
    content: '续费功能正在开发中...',
    showCancel: false
  })
}

const endOrder = async () => {
  const confirmed = await showConfirm('确定要结束当前订单吗？')
  if (confirmed) {
    const result = await orderStore.completeOrder(order.value.id)
    if (result.success) {
      order.value.status = 'completed'
      order.value.actualEndTime = new Date()
      showSuccess('订单已结束')
    } else {
      showError(result.message || '结束失败')
    }
  }
}

const rateOrder = () => {
  uni.showModal({
    title: '评价功能',
    content: '评价功能正在开发中...',
    showCancel: false
  })
}

const rebookOrder = () => {
  // 选择相同座位
  const success = seatStore.selectSeat(order.value.seatId)
  if (success) {
    uni.navigateTo({
      url: '/pages/booking/booking'
    })
  } else {
    showError('该座位当前不可用')
  }
}

// 生命周期
onMounted(() => {
  // 检查页面访问权限
  if (!checkPageAccess({
    requireLogin: true,
    fallbackUrl: '/pages/order/order'
  })) {
    return
  }

  // 获取订单ID
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const orderId = currentPage.options.id

  if (orderId) {
    // 查找订单
    order.value = orderStore.getOrderById(parseInt(orderId))

    if (!order.value) {
      showError('订单不存在')
      uni.navigateBack()
      return
    }

    // 开始倒计时
    if (order.value.status === 'in_progress') {
      remainingTimeInterval.value = setInterval(() => {
        // 触发响应式更新
      }, 1000)
    }
  } else {
    showError('订单ID不存在')
    uni.navigateBack()
  }
})

onUnmounted(() => {
  if (remainingTimeInterval.value) {
    clearInterval(remainingTimeInterval.value)
  }
})
</script>

<style lang="scss" scoped>
.order-detail-page {
  min-height: 100vh;
  background: var(--color-background);
  padding: 16px;
}

// 卡片基础样式
.card {
  background: white;
  border-radius: var(--radius-xl);
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: var(--shadow-sm);
}

.card-header {
  margin-bottom: 16px;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text-primary);
}

// 订单状态卡片
.status-card {
  .status-header {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 20px;
  }

  .status-icon {
    width: 60px;
    height: 60px;
    border-radius: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;

    &.status-pending {
      background: rgba(255, 149, 0, 0.1);
      color: var(--color-warning);
    }

    &.status-confirmed {
      background: rgba(0, 122, 255, 0.1);
      color: var(--color-primary);
    }

    &.status-progress {
      background: rgba(52, 199, 89, 0.1);
      color: var(--color-success);
    }

    &.status-completed {
      background: rgba(142, 142, 147, 0.1);
      color: var(--color-text-secondary);
    }

    &.status-cancelled {
      background: rgba(255, 59, 48, 0.1);
      color: var(--color-error);
    }
  }

  .status-info {
    flex: 1;
  }

  .status-title {
    font-size: 20px;
    font-weight: bold;
    color: var(--color-text-primary);
    display: block;
    margin-bottom: 4px;
  }

  .status-desc {
    font-size: 14px;
    color: var(--color-text-secondary);
  }

  .remaining-time {
    background: rgba(52, 199, 89, 0.1);
    border-radius: var(--radius-lg);
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .time-label {
    font-size: 14px;
    color: var(--color-success);
  }

  .time-value {
    font-size: 24px;
    font-weight: bold;
    color: var(--color-success);
  }
}

// 座位信息卡片
.seat-card {
  .seat-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    background: var(--color-background);
    border-radius: var(--radius-lg);
  }

  .seat-main {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .seat-number {
    font-size: 28px;
    font-weight: bold;
    color: var(--color-text-primary);
  }

  .seat-area {
    font-size: 14px;
    color: var(--color-text-secondary);
    padding: 2px 8px;
    background: white;
    border-radius: var(--radius-sm);
    align-self: flex-start;
  }

  .seat-price {
    text-align: right;
  }

  .price-text {
    font-size: 18px;
    font-weight: bold;
    color: var(--color-primary);
  }
}

// 时间信息卡片
.time-card {
  .time-details {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .time-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid var(--color-border);

    &:last-child {
      border-bottom: none;
    }
  }

  .time-label {
    font-size: 14px;
    color: var(--color-text-secondary);
  }

  .time-value {
    font-size: 16px;
    color: var(--color-text-primary);
    font-weight: 500;
  }
}

// 费用明细卡片
.cost-card {
  .cost-details {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .cost-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;

    &.discount {
      .cost-value {
        color: var(--color-success);
      }
    }

    &.total {
      padding-top: 16px;

      .cost-label {
        font-size: 18px;
        font-weight: 600;
      }

      .cost-value {
        font-size: 20px;
        font-weight: bold;
        color: var(--color-error);
      }
    }
  }

  .cost-label {
    font-size: 14px;
    color: var(--color-text-secondary);
  }

  .cost-value {
    font-size: 16px;
    color: var(--color-text-primary);
    font-weight: 500;
  }

  .cost-divider {
    height: 1px;
    background: var(--color-border);
    margin: 8px 0;
  }
}

// 支付信息卡片
.payment-card {
  .payment-details {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .payment-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
  }

  .payment-label {
    font-size: 14px;
    color: var(--color-text-secondary);
  }

  .payment-value {
    font-size: 14px;
    color: var(--color-text-primary);
    font-weight: 500;
  }

  .payment-status {
    padding: 4px 8px;
    border-radius: var(--radius-sm);
    font-size: 12px;
    font-weight: 500;

    &.pending {
      background: rgba(255, 149, 0, 0.1);
      color: var(--color-warning);
    }

    &.paid {
      background: rgba(52, 199, 89, 0.1);
      color: var(--color-success);
    }

    &.refunded {
      background: rgba(142, 142, 147, 0.1);
      color: var(--color-text-secondary);
    }
  }
}

// 操作按钮
.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 24px;
}

.btn {
  width: 100%;
  height: 48px;
  border: none;
  border-radius: var(--radius-lg);
  font-size: 16px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all var(--transition-normal);

  &:active {
    transform: scale(0.98);
  }

  &.btn-primary {
    background: var(--color-primary);
    color: white;
    box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);
  }

  &.btn-secondary {
    background: transparent;
    color: var(--color-text-secondary);
    border: 1px solid var(--color-border);
  }
}

// 加载状态
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.loading-icon {
  width: 40px;
  height: 40px;
  border: 3px solid var(--color-border);
  border-top-color: var(--color-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-text {
  font-size: 16px;
  color: var(--color-text-secondary);
}

// 响应式适配
@media (max-width: 375px) {
  .order-detail-page {
    padding: 12px;
  }

  .card {
    padding: 16px;
  }

  .status-icon {
    width: 50px;
    height: 50px;
    border-radius: 25px;
    font-size: 20px;
  }

  .status-title {
    font-size: 18px;
  }

  .seat-number {
    font-size: 24px;
  }

  .price-text {
    font-size: 16px;
  }

  .time-value {
    font-size: 20px;
  }
}
</style>
